package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/25 10:36
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        Table table = tenv.fromDataStream(waterSensorStream);
        
        
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")))
            .execute()
            .print();*/
    
        tenv.createTemporaryFunction("my_avg", MyAvg.class);
        /*table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")))
            .execute()
            .print();*/
        
        tenv.sqlQuery("select id, my_avg(vc) from " + table + " group by id" ).execute().print();
        
        
        
        
    }
    
    public static class Avg{
        public Double sum = 0D;
        public Long count = 0L;
        
        public Double avg(){
            return sum * 1.0 / count;
        }
        
    }
    
    // 泛型1: 指的是最终的计算结果的类型
    public static class MyAvg extends AggregateFunction<Double, Avg>{
        
    
        // 初始化累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        // sum(vc)
        public void accumulate(Avg avg, Double vc){
            // 更新累加器中的属性的值就可以了
            avg.sum+= vc;
            avg.count++;
        }
    
        // 返回最终聚合的值
        @Override
        public Double getValue(Avg acc) {
            return acc.avg();
        }
    }
    
    
}

